package com.tengju.bff.interfaces.manage.crm.user.facade;

import com.google.common.collect.Lists;
import com.tengju.bff.interfaces.manage.star.vo.SurveyConfigVO;
import com.tengju.bff.interfaces.manage.crm.user.assembler.ArchiveAssembler;
import com.tengju.bff.interfaces.manage.crm.user.vo.ArchiveContentVo;
import com.tengju.user.application.archives.ArchiveService;
import com.tengju.user.domain.model.survey.*;
import com.tengju.user.domain.model.user.UserIdCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArchiveManageFacade {

    private SurveyRepotiory surveyRepotiory;
    private ArchiveService archiveService;

    @Autowired
    public ArchiveManageFacade(SurveyRepotiory surveyRepotiory, ArchiveService archiveService) {
        this.surveyRepotiory = surveyRepotiory;
        this.archiveService = archiveService;
    }

    public SurveyConfigVO getSurveyConfig(SurveyId surveyId, UserIdCode idCode) {

        //获取配置
        SurveyConfig surveyConfig = surveyRepotiory.getConfigById(surveyId.getValue());

        if (surveyConfig == null || surveyConfig.getQuestionConfigList() == null) {
            return null;
        }

        //获取已填写的选项
        List<SurveyQuestionResult> filledOptions = archiveService.getFilledOption(surveyId, idCode);

        return ArchiveAssembler.configModelToVO(surveyConfig,filledOptions);
    }

    public List<ArchiveContentVo> getContent(SurveyId surveyId, UserIdCode idCode) {

        SurveyContent archiveContent = surveyRepotiory.getContent(idCode, surveyId);

        List<ArchiveContentVo> result = Lists.newArrayList();

        if (archiveContent == null || CollectionUtils.isEmpty(archiveContent.getQuestionResults())) {
            return result;
        }

        return archiveContent.getQuestionResults().stream()
                .filter(questionResult -> !StringUtils.isEmpty(questionResult.getQueryTitle()))
                .map(ArchiveAssembler::contentModelToVO)
                .collect(Collectors.toList());

    }

}
